// import {TableElement} from './TableElement';
import {Constant} from '../Constant.js';
import {QueryData} from './QueryData.js';
class DragElements {
  constructor(appId = '', keys = [], elements = {}, query = new QueryData()) {
    this.appId = appId;
    this.keys = keys;
    this.elements = elements;// {key: TableElement}
    this.query = query;
    this.appName = '';
  }

  get elementsValue() {
    return Object.keys(this.elements).map(key => this.elements[key]);
  }

  setCustomElementValue(count) {
    Object.keys(this.elements).forEach(elementId =>{
      const element = this.elements[elementId];
      if (element.isCustomElement) {
        element.resetDataList(count, document.getElementById(elementId).children[0].children[0].value);
      }
    });
  }
  clearElementDataList() {
    this.elementsValue.forEach((element) =>{
      element.elementDataList = [];
    });
  }
  addElement(tableElement) {
    const elementId = tableElement.elementView.id;
    this.elements[elementId] = tableElement;
  }
  putAppRecordDatasIntoElements(records) {
    let rowCount = records.length;
    records.forEach((record)=>{
      // put record's value into dragElements according to record's keys
      rowCount += this.addRecordDataIntoElements(record);
    });
    this.setCustomElementValue(rowCount);
  }
  addRecordDataIntoElements(record, isSubTable = true) {
    let rowCount = 0;
    this.keys.forEach(key =>{
      const recordValue = record[key];
      if (recordValue !== undefined) {
        const id = `${key}_${this.appId}`;
        if (recordValue.type !== Constant.APP_DATA_TYPE_SUBTABLE) {
          this.addRecordValueIntoElements(recordValue, id);
        } else if (isSubTable) {
          // fill common record value for table's over value
          rowCount += (recordValue.value.length - 1);
          for (let i = 1; i < recordValue.value.length; i++) {
            this.addRecordDataIntoElements(record, false);
          }
          this.addRecordValueIntoElements(recordValue, id);
        }
      }
    });
    return rowCount;
  }
  addRecordValueIntoElements(recordValue, id) {
    const talbeElement = this.elements[id];
    switch (recordValue.type) {
      case Constant.APP_DATA_TYPE_CHECK_BOX: case Constant.APP_DATA_TYPE_MULTI_SELECT:
        talbeElement.putDatasIntoDataList(recordValue.value);
        break;
      case Constant.APP_DATA_TYPE_USER_SELECT: case Constant.APP_DATA_TYPE_GROUP_SELECT: case Constant.APP_DATA_TYPE_ORGANIZATION_SELECT:
        (recordValue.value).forEach(userInfo =>{
          talbeElement.putDataIntoDataList(userInfo.name);
        });
        break;
      case Constant.APP_DATA_TYPE_DATE:
        talbeElement.putDataIntoDataList(recordValue.value ? (recordValue.value) : '');
        break;
      case Constant.APP_DATA_TYPE_SUBTABLE:
        if (recordValue.value.length) {
          (Object.keys((recordValue.value)[0].value)).forEach(tableKey =>{
            const tempId = `${id}_${tableKey}`;
            (recordValue.value).forEach(row =>{
              const tempData = (row.value)[tableKey];
              if (tempData) {
                this.addRecordValueIntoElements(tempData, tempId);
              }
            });
          });
        }
        break;
      default:
        talbeElement.putDataIntoDataList(recordValue.value ? recordValue.value : '');
    }
  }
  bindPoint(anchorsSite) {
    jsPlumb.ready(() => {
      const common = (anchor) =>{
        return {
          endpoint: ['Dot', {
            radius: 10,
            fill: '#48A8E8'
          }], // 端点的形状
          connectorStyle: {
            strokeWidth: 2,
            stroke: '#48A8E8',
            // strokeStyle: '#61B7CF',
            joinstyle: 'round',
            outlineStroke: '',
            outlineWidth: 2
          }, // 连接线的颜色，大小样式
          connectorHoverStyle: {
            lineWidth: 2,
            stroke: 'red',
            outlineWidth: 2,
            outlineColor: ''
          },
          paintStyle: {
            strokeStyle: '#1e8151',
            stroke: 'green',
            fill: '#48A8E8',
            fillStyle: '#1e8151',
            radius: 6,
            lineWidth: 2
          },
          ReattachConnections: false,
          hoverPaintStyle: {stroke: 'lightblue'},
          isSource: anchor === Constant.ANCHORS_SITE_RIGHT, // 是否可以拖动（作为连线起点）
          connector: ['Flowchart'], // 连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
          isTarget: anchor === Constant.ANCHORS_SITE_LEFT, // 是否可以放置（连线终点）
          connectorOverlays: [
            ['Arrow', {
              width: 10,
              length: 10,
              location: 1
            }],
            ['Arrow', {
              width: 10,
              length: 10,
              location: 0.2
            }],
            ['Arrow', {
              width: 10,
              length: 10,
              location: 0.7
            }],
            ['Label', {
              label: '',
              cssClass: '',
              labelStyle: {
                color: 'red'
              },
              events: {
                click: function(labelOverlay, originalEvent) {
                }
              }
            }]
          ]
        };
      };
      this.elementsValue.forEach(point =>{
        const id = point.elementView.id;
        const uuid = `uuid_${id}`;
        if (point.isNeedBindPoint) {
          if (anchorsSite === Constant.ANCHORS_SITE_BOTH) {
            jsPlumb.addEndpoint(id, {
              anchor: Constant.ANCHORS_SITE_LEFT,
              uuid: `${uuid}_${Constant.ANCHORS_SITE_LEFT}`
            }, common(Constant.ANCHORS_SITE_LEFT));
            jsPlumb.addEndpoint(id, {
              anchor: Constant.ANCHORS_SITE_RIGHT,
              uuid: `${uuid}_${Constant.ANCHORS_SITE_RIGHT}`
            }, common(Constant.ANCHORS_SITE_RIGHT));
          } else {
            jsPlumb.addEndpoint(id, {
              anchor: anchorsSite,
              uuid: `${uuid}_${anchorsSite}`
            }, common(anchorsSite));
          }
        }
      });
    });
  }
  bindCheckBoxButtonChange(change) {
    this.elementsValue.forEach(element =>{
      if (element.isNeedBindPoint) {
        const elementView = element.elementView;
        const checkBox = document.createElement('input');
        checkBox.type = 'checkbox';
        checkBox.style.margin = '1px';
        checkBox.style.marginLeft = '5px';
        checkBox.style.verticalAlign = 'middle';
        checkBox.id = `checkbox_${elementView.id}`;
        checkBox.addEventListener('change', (event) =>{
          change(event.target);
        });
        elementView.appendChild(checkBox);
      }
    });
  }
  hidePoints() {
    this.elementsValue.forEach(element =>{
      jsPlumb.hide(element.elementView, true);
    });
  }
  showPoints() {
    this.elementsValue.forEach(element =>{
      jsPlumb.show(element.elementView, true);
    });
  }
  bindDoubleClick(ondbClick) {
    this.elementsValue.forEach(element =>{
      const elementView = element.elementView;
      elementView.addEventListener('dblclick', (event) =>{
        ondbClick(element);
      });
    });
  }
}

export {
  DragElements
};